import axios from 'axios';
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Checkbox, NavBar, Stepper, SubmitBar, Notify } from 'react-vant'
import './App.css'
import { debounce } from 'lodash'
const App = () => {
  // 获取购物车仓库数据
  const cartList = useSelector(state => state.cart.cartList);
  // 获取dispatchs
  const dispatch = useDispatch();
  // 全选状态
  const allCheck = cartList.every(v => v.state)
  // 获取购物车列表数据
  const getCarList = async () => {
    const resp = await axios.get('/api/list');
    console.log(resp.data)
    dispatch({ type: 'initCartList', payload: resp.data.data })
  }
  // 总价计算
  const allState = cartList.filter(v => {
    return v.state
  }).reduce((p, n) => {
    return p + (n.count * n.price) 
  }, 0) * 0.9
  const handleSubmit = debounce(() => {
    console.log('提交订单')
  }, 400)

  useEffect(() => {
    // getCarList()
  }, [])

  return (
    <div>
      <NavBar title="购物车" leftText=""></NavBar>

      <div className="list">
        {
          cartList.map(v => {
            return (
              <dl key={v.id} style={{ display: 'flex' }}>
                <dt>
                  <Checkbox checked={v.state} onChange={() => dispatch({ type: 'oneState', payload: v })}></Checkbox>
                </dt>
                <dd>
                  <img src={v.image} width="150" height="120" alt="" />
                </dd>
                <dd>
                  <h3>{v.title}</h3>
                  <p>{v.desc}</p>
                  <p style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span><s>原价：{v.price}</s></span>
                    <span>现价： {(v.price * v.dis).toFixed(1)}元</span>
                  </p>
                  <Stepper 
                    value={v.count}
                    onPlus={() => dispatch({ type: 'add', payload: v })}
                    onMinus={() => dispatch({ type: 'sub', payload: v })}
                    min={1}
                    onOverlimit={() => Notify.show({ type: 'warning', message: '数量不可减少数量小于1' }) }
                  ></Stepper>
                </dd>
              </dl>
            )
          })
        }
      </div>
      <div style={{ height: 50 }}>
        <SubmitBar
          price={allState * 100}
          buttonText="提交订单"
          onSubmit={() => handleSubmit()}
        >
          <Checkbox checked={allCheck} onChange={() => dispatch({
            type: 'allState', payload: !allCheck
          })}>全选</Checkbox>
        </SubmitBar>
      </div>

    </div>
  )
}

export default App